package com.zrb.mobile;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.applib.utils.AppSetting;
 
import com.zrb.mobile.adapter.model.AdsDtoResult;
import com.zrb.mobile.adapter.model.ProjectUserDto;
import com.zrb.mobile.adapter.model.UserDtos;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.CenterProgressWebView;
import com.zrb.mobile.ui.CenterProgressWebView.IOnJsPrompt;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CollectionHelper.checkCollection;
import com.zrb.mobile.utility.CollectionHelper.onCollectionListener;
import com.zrb.mobile.utility.AlertDialog;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ViewUtil;
import com.zrb.mobile.utility.ZrbRestClient;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ProjectDetailActivity extends BaseCheckloginActivity implements
		OnClickListener, onCollectionListener, checkCollection, IOnJsPrompt {
	// public String ACTION_NAME_SENVEN = "user_my_ownprojects";
	private long curfindmoneyId;
	boolean isFavorite = false;
	Dialog AuthDialog;
	TextView btnfavorite;
	CollectionHelper mCollectionHelper;
	CenterProgressWebView mWebView;
	String title;
	// public String ACTION_NAME_ONE = "discover_content";
	// public String ACTION_NAME_FOUR = "discover_detail_content";
	// public String ACTION_NAME_THREE = "my_publish";
	private int position;
	private String from;
	Dialog CheckPwdDialog;
	

	public static void launch (Context mActivity,long id,String title){
		
		 if(mActivity==null) return;
		 Intent it = new Intent(mActivity, ProjectDetailActivity.class);
		 it.putExtra("id", id );
		 it.putExtra("title", title );
		  mActivity.startActivity(it);
	}
	

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.news_web_content);

		if (bundle != null)
			restoreSelf(bundle);
		else {
			curfindmoneyId = this.getIntent().getLongExtra("id", -1);
			title = this.getIntent().getStringExtra("title");
			from = this.getIntent().getStringExtra("from");
			position = this.getIntent().getIntExtra("position", -1);
		}
		init();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putLong("newid", curfindmoneyId);
		outState.putString("title", title);
		outState.putString("from", from);
		outState.putInt("position", position);
	}

	private void restoreSelf(Bundle savedInstanceState) {
		curfindmoneyId = savedInstanceState.getLong("newid");
		title = savedInstanceState.getString("title");
		from = savedInstanceState.getString("from");
		position = savedInstanceState.getInt("position");
	}

	private void init() {

		mCollectionHelper = new CollectionHelper(this, Constants.FocusProject);
		mCollectionHelper.setOnCollectionListener(this);
		mCollectionHelper.setOncheckCollection(this);

		this.findViewById(R.id.title_left_root).setOnClickListener(this);
		this.findViewById(R.id.btn_share).setOnClickListener(this);
		this.findViewById(R.id.btn_font).setOnClickListener(this);
		this.findViewById(R.id.bottombar).setVisibility(View.VISIBLE);
		

		btnfavorite = (TextView) this.findViewById(R.id.btn_favorite);
		btnfavorite.setVisibility(View.VISIBLE);
		btnfavorite.setOnClickListener(this);

		mWebView = (CenterProgressWebView) this.findViewById(R.id.webView1);
		mWebView.setOnPageListener(null);
		// mWebView.addJavascriptInterface(this, "localApi");
		mWebView.setOnJsPromptListener(this);
		// http://backend.zhaorongbao.com:8090/newsapp/newsDetails?id=26
		// String url="file:///android_asset/detail/detail.html";
		String url = AppSetting.BASE_URL + "projectApi/getProjectDetail?id="
				+ curfindmoneyId;
		CommonUtil.InfoLog("url", url);
		mWebView.loadUrl(url);
		loaduserInfo();
		if (AppSetting.curUser != null)
			mCollectionHelper.checkCollect(curfindmoneyId);
		 
			
	}

	
	void loaduserInfo(){
		//businessCard/getProjectUserInfo?projectId=33020
		ZrbRestClient.get("businessCard/getProjectUserInfo?projectId="+curfindmoneyId , null,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,Throwable arg3) {
						CommonUtil.showToast("网络超时,请重新连接", ProjectDetailActivity.this);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
						String results = new String(arg2);
							try {
								
								Gson gson = new Gson();
								ProjectUserDto tmpDto = gson.fromJson(results, ProjectUserDto.class);
								 ((TextView) ProjectDetailActivity.this.findViewById(R.id.textView1)).setText(tmpDto.data.realName);
								 ((TextView) ProjectDetailActivity.this.findViewById(R.id.textView3)).setText(tmpDto.data.industryName+tmpDto.data.org+tmpDto.data.postion);
								 
								 ImageView tmpimg= (ImageView)ProjectDetailActivity.this.findViewById(R.id.iv_avatar);
								 ViewUtil.showUserAvatar(tmpimg,AppSetting.mediaServer+tmpDto.data.avatar);
								 
					        } catch (Exception e) {
							   CommonUtil.showToast("服务端数据异常",ProjectDetailActivity.this);//fail:"+e.getMessage()
						    }
					}
				});
		
	}
	@Override
	public void onCollectionEvent() {
		// TODO Auto-generated method stub
		// showToast(!isFavorite ?"已关注":"取消关注", Project_info_lience.this);
		isFavorite = !isFavorite;
		btnfavorite.setSelected(isFavorite);
		btnfavorite.setText(isFavorite ? "已关注" : "关 注");
		btnfavorite.setEnabled(false);
		if ("1".equals(from)) {
			Intent intent1 = new Intent(Constants.FocusNum_Find_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("from", "1");
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		} else if ("2".equals(from)) {
			Intent intent1 = new Intent(Constants.FocusNum_PUBLISE_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("from", "1");
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		} else if ("3".equals(from)) {
			Intent intent1 = new Intent(Constants.FocusNum_MYPROJECT_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("from", "1");
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		}
		else if ("4".equals(from)) {
			Intent intent1 = new Intent(Constants.PRONum_ATTENTION_mainlist);
			intent1.putExtra("position", position);
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		}
		else if ("5".equals(from)) {
			Intent intent1 = new Intent(Constants.FocusNum_Find_mainlist);
			intent1.putExtra("from", "1");
			intent1.putExtra("position", position);
			intent1.putExtra("attention", isFavorite ? 1 : 0);
			sendBroadcast(intent1);
		}
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				btnfavorite.setEnabled(true);
			}

		}, 2000);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_left_root:
			if (mWebView.canGoBack()) {
				mWebView.goBack();
				return;
			}
			;
			this.finish();
			break;
		case R.id.btn_share:
			shareLink();
			break;
		case R.id.btn_favorite:

			if (AppSetting.curUser == null) {
				showLoginDialog();

			} else {
				mCollectionHelper.onClickCollect(curfindmoneyId, !isFavorite);

			}
			break;
		case R.id.btn_font:
			callServerPhone();
			break;
		default:
			break;
		}
	}

	private void shareLink() {
		// String imageLink=AppSetting.BASE_URL+"newsapp/newsDetails?id="+newid;
		Intent intent = new Intent(ProjectDetailActivity.this,
				News_ShareActivity.class);
		intent.putExtra("title", title);
		// intent.putExtra("url",imageLink);
		intent.putExtra("url", mWebView.getUrl());
		startActivity(intent);
	}

	public void callServerPhone() {
		 new AlertDialog(ProjectDetailActivity.this).builder()
		   .setMsg(String.format(ProjectDetailActivity.this.getString(R.string.user_center_profile_edit_org_authtrue1), Constants.serverPhone))
		   .setPositiveButton("呼叫", new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +Constants.serverPhone));//"400-688-0101"
				ProjectDetailActivity.this.startActivity(intent);
			}
		    }).setNegativeButton("取消").show();
		 
	}
	
	

	@Override
	public void onhasCollection(boolean ishas) {
		// TODO Auto-generated method stub
		isFavorite = ishas;
		btnfavorite.setSelected(isFavorite);
		btnfavorite.setText(isFavorite ? "已关注" : "关 注");
	 
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
			case 500:
				if (AppSetting.curUser != null)
					mCollectionHelper.checkCollect(curfindmoneyId);
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void PromptInfo(String message, String defaultValue) {
		// TODO Auto-generated method stub
		Log.e("PromptInfo", message);//id
		if(TextUtils.isEmpty(message)) return;
		if(!message.contains(",")) return;
		//CommonUtil.showToast(message+"|"+defaultValue, this);
		 String[] tmpArr=message.split(",");
 
		  if( "1".equals(tmpArr[0])){
			  callServerPhone();
	      }
		  else if( "2".equals(tmpArr[0]))
	      {
	    	// final int  pId =  Integer.parseInt(tmpArr[1]);
	    	// final String  pName = tmpArr[2];
	    	  DialogBuilder builder2 = new DialogBuilder(ProjectDetailActivity.this);
	   		  builder2.setParentlayout(R.layout.custom_ucenter_dialog);
	          builder2.setContentView(R.layout.u_center_verify_send_email); //ac_dialog_cancel; 
	          final EditText pwdedit=(EditText)builder2.getCurContentView().findViewById(R.id.pwd_editText);
	          if( null != AppSetting.curUser&&!TextUtils.isEmpty(AppSetting.curUser.uemail)){
 		         pwdedit.setText(AppSetting.curUser.uemail);
	          }
 	          builder2.setCloseOnclick(new OnClickListener(){
	   			    @Override
	  				public void onClick(View arg0) {
	   			    	if(arg0.getId()==R.id.btn_cancel){
	   			    		CheckPwdDialog.dismiss();
	   			    		return;
	   			    	}
	   			    	if(pwdedit.getText()==null||pwdedit.getText().toString()==""){
	   			    		CommonUtil.showToast("请输入邮箱", ProjectDetailActivity.this);
	   			    		return;
	   			    	}
	   			    	if(!CommonUtil.isEmail(pwdedit.getText().toString())){
  							CommonUtil.showToast("请输入正确的邮箱", ProjectDetailActivity.this);
  							return;
  						}
	   			    	CheckPwdDialog.dismiss();
	  					sendEmail(pwdedit.getText().toString(), curfindmoneyId, title);
   	  				 }
	  		   }); 
	          CheckPwdDialog = builder2.create();
	          CheckPwdDialog.show();
		
	      }
		  else if( "3".equals(tmpArr[0])){
	    	  if(tmpArr[1].equals("0")) return;
 	  	  	  Intent it = new Intent(this, BaiduMapActivity.class);
 		 	  it.putExtra("latitude", Double.parseDouble(tmpArr[2]));
		 	  it.putExtra("longitude", Double.parseDouble(tmpArr[1]));
		 	  it.putExtra("address", "");
		 	  startActivity(it);
 	      }
		  else if( "4".equals(tmpArr[0])){
			  
			  imageBrower();
		  }
 	}

	private void imageBrower() {
	 
		
		 ZrbRestClient.get("projectApi/getPhotoList?id="+curfindmoneyId , null,
					new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2,Throwable arg3) {
							CommonUtil.showToast("网络超时,请重新连接", ProjectDetailActivity.this);
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							// TODO Auto-generated method stub
							String results = new String(arg2);
 							try {
 								
 								   JSONArray jsonObject2 =new JSONArray(results);
 							 
 								   String[] urls=new String[jsonObject2.length()];
 								   String[] picdes= new String[jsonObject2.length()];
  						     	   for(int i=0;i<jsonObject2.length();i++){
  						     		  urls[i]=AppSetting.mediaServer+"/"+jsonObject2.getJSONObject(i).getString("url");
  						     	      picdes[i]=jsonObject2.getJSONObject(i).getString("remark"); 
   						     	   }
  						     		
								 
  						     	   Intent intent = new Intent(ProjectDetailActivity.this, ImagePagerActivity.class);
  						     	   intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
  						        	intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INFOS, picdes);
  								   intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
  								   startActivity(intent);
						        } catch (Exception e) {
								   CommonUtil.showToast("服务端数据异常",ProjectDetailActivity.this);//fail:"+e.getMessage()
							    }
						}
					});
	}
	
	private void sendEmail(String email,long pId,String pName){
		 RequestParams param = new RequestParams();
		 param.put("email", email);
		 param.put("projectId", pId);
		 param.put("projectName", pName);
		 
		 CommonUtil.InfoLog("sendEmail", param.toString());
		 ZrbRestClient.post("proEmailApi/insert" , param,
						new AsyncHttpResponseHandler() {

							@Override
							public void onFailure(int arg0, Header[] arg1, byte[] arg2,Throwable arg3) {
								CommonUtil.showToast("网络超时,请重新连接", ProjectDetailActivity.this);
							}

							@Override
							public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
								// TODO Auto-generated method stub
								String results = new String(arg2);
								//Log.e("tag", results);
								try {
									  Gson gson = new Gson();
									  UserDtos tmpDto = gson.fromJson(results,UserDtos.class);
									  CommonUtil.showToast(tmpDto.res==1 ? "提交成功":tmpDto.msg, ProjectDetailActivity.this);
	 								 
							        } catch (Exception e) {
									   CommonUtil.showToast("服务端数据异常",ProjectDetailActivity.this);//fail:"+e.getMessage()
								    }
							}
						});
	}
	
	@Override
	public void ReceivedTitle(String title) {
		// TODO Auto-generated method stub
		
	}
}
